package com.zly.lab.blog.config;

import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

//自定义区域解析器
@Configuration
public class MyLocalResolver implements LocaleResolver {
    //区域解析器
    @NotNull
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        //从头信息获取
        String header = request.getHeader("Accept-Language");
        String l = request.getParameter("l");
        //创建locale
        Locale locale =null;
        //解析
        if (l!=null&&l!=""){
            String[] s = l.split("_");
            locale = new Locale(s[0],s[1]);
        }else {
            String[] split = header.split(",")[0].split("-");
            locale = new Locale(split[0],split[1]);
        }
        //用户手动切换(优先)
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

    }
    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocalResolver();
    }
}
